package com.jqsoft.nursepad;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.http.SslError;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import android.telephony.TelephonyManager;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private X5WebView mWebView;

    private String mymei;

    NetWorkStateReceiver netWorkStateReceiver;
    private String myurl="";


    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);

         getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);

        String androidID = Settings.Secure.getString(MainActivity.this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;

        mymei= getMacAddr();
        mWebView=(X5WebView)findViewById(R.id.webview);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);     //设置js可以直接打开窗口，如window.open()，默认为false
        mWebView.getSettings().setJavaScriptEnabled(true);     //是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        mWebView.getSettings().setSupportZoom(true);           //是否可以缩放，默认true
        mWebView.getSettings().setAllowFileAccess(true);       // 设置允许访问文件数据
        mWebView.getSettings().setBuiltInZoomControls(true);   //是否显示缩放按钮，默认false
        mWebView.getSettings().setUseWideViewPort(true);       //设置此属性，可任意比例缩放。大视图模式
        mWebView.getSettings().setLoadWithOverviewMode(true);  //和setUseWideViewPort(true)一起解决网页自适应问题
        mWebView.getSettings().setAppCacheEnabled(true);       //是否使用缓存
        mWebView.getSettings().setDomStorageEnabled(true);     //DOM Storage


//        mWebView.setWebViewClient(new android.webkit.WebViewClient() {
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
//            }
//        });
        //   mWebView.addJavascriptInterface(new JsInterface(MainActivity.this), "PartnerHome");





        mWebView.setVerticalScrollbarOverlay(true);
        //mWebView
        mWebView.getSettings().setJavaScriptEnabled(true);

        if("".equals(mymei) || mymei==null){

        }else {
            mymei=   mymei.replace(":","%3a");
        }
        //支持缩放
//        mWebView.getSettings().setSupportZoom(true);
////设置出现缩放工具
//        mWebView.getSettings().setBuiltInZoomControls(true);
////扩大比例的缩放
//        mWebView.getSettings().setUseWideViewPort(true);
////js交互
//        mWebView.getSettings().setJavaScriptEnabled(true);
////        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        mWebView.getSettings().setLoadWithOverviewMode(true);

//        String url="https://www.cnblogs.com/dame/p/8085917.html";
        String url="http://192.168.44.140:8091/DisplayPages/RoomElderInfo/?mac="+mymei;
//       String url="http://rjkfyy.365yiyang.com/DisplayPages/RoomElderInfo/?mac="+mymei;
//        String url="http://wit.365yiyang.com/DisplayPages/NurseStation/%E9%9D%99%E5%AE%89/FloorDetailInfo.aspx?speed=30&floorID=51e419db-cc09-4480-9986-6f035b1eb9a9&ddlOrg=39008901-68d7-4fa5-bd04-959976764d8a";

//        String url="http://10.1.82.8:8090/test/floor12.html";

        myurl=url;
        mWebView.loadUrl(url);

//        Toast.makeText(getApplicationContext(),url,Toast.LENGTH_LONG).show();


        //添加客户端支持
//        mWebView.setWebChromeClient(new WebChromeClient());



//        mWebView.setWebViewClient(new WebViewClient() {
//
//                                     @Override
//                                     public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                                         view.loadUrl(url);
//                                         return false;
//                                     }
//
//                                     @Override
//                                     public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                                         super.onPageStarted(view, url, favicon);
//                                      //   progressDialog.show();
//                                     }
//
//                                     @Override
//                                     public void onPageFinished(WebView view, String url) {
//                                         super.onPageFinished(view, url);
//                                        // Log.d("WEBCLIENT", "onPageFinished");
//                                     }
//
//                                     @Override
//                                     public void onLoadResource(WebView view, String url) {
//                                         super.onLoadResource(view, url);
//                                        // Log.d("WEBCLIENT","onLoadResource");
//
//                                         if(mWebView.getProgress() == 100) {
//                                        //     progressDialog.dismiss();
//                                         }
//                                     }
//                                 });


       // mymei  =  androidID;

//
//        AlertDialog.Builder builder=new AlertDialog.Builder(this);
//
//        builder.setTitle("mac");
//        builder.setMessage(mymei);
//        builder.setPositiveButton("我知道了",
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                });
//        AlertDialog dialog=builder.create();
//        dialog.show();

    }



    @JavascriptInterface
    public void setTimeOut(){
        //MyDebug.log(TAG,"setTimeOut");
        Log.e("tst","setTimeOut");
    }



    private String getmei(){
        String androidID = Settings.Secure.getString(MainActivity.this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
// within my emulator it returns: 000000000000000

      String s1=  MobileInfoUtil.getIMEI(MainActivity.this);
        String s2=  MobileInfoUtil.getIMSI(MainActivity.this);
        if(!TextUtils.isEmpty(s1)){

            return s1;
        }
        return "";
    }
    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:",b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            return true;//不执行父类点击事件
        }
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }


    //在onResume()方法注册
    @Override
    protected void onResume() {
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        System.out.println("注册");
        super.onResume();
    }

    //onPause()方法注销
    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);
        System.out.println("注销");
        super.onPause();
    }

    @Subscribe
    public void onEventMainThread(FirstEvent event) {

        String msg =  event.getMsg();
//        Log.d("harvic", msg);
        if(msg==null )
            msg="";
       mWebView.loadUrl(myurl);
//        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventB
    }
}